"""
AI 服务 API 路由
提供文生图等 AI 功能的 REST API 接口
"""

import time
from fastapi import APIRouter, HTTPException, status
from loguru import logger

from app.core.config import settings
from app.schemas.ai_schemas import (
    ErrorResponse,
    HealthResponse,
    ImageInfo,
    TextToImageRequest,
    TextToImageResponse,
)
from app.services.ai.factory import AIServiceFactory

router = APIRouter(prefix="/ai", tags=["AI服务"])


@router.get(
    "/health",
    response_model=HealthResponse,
    summary="健康检查",
    description="检查 AI 服务状态和可用功能",
)
async def health_check():
    """健康检查接口"""
    return HealthResponse(
        status="healthy",
        version=settings.APP_VERSION,
        providers=["minimax"],
        features=["text-to-image"],
    )


@router.get(
    "/debug-status",
    summary="调试状态",
    description="获取当前 MiniMax 调试模式状态",
)
async def debug_status():
    """获取调试状态"""
    return {
        "minimax_debug_mode": settings.MINIMAX_DEBUG_MODE,
        "description": "调试模式使用模拟数据，生产模式使用真实API",
        "current_mode": "调试模式" if settings.MINIMAX_DEBUG_MODE else "生产模式",
        "api_key_configured": bool(settings.MINIMAX_API_KEY),
    }


@router.post(
    "/toggle-debug-mode",
    summary="切换调试模式",
    description="切换 MiniMax 调试模式开关",
)
async def toggle_debug_mode():
    """切换调试模式"""
    try:
        # 切换调试模式状态
        new_debug_mode = not settings.MINIMAX_DEBUG_MODE
        settings.MINIMAX_DEBUG_MODE = new_debug_mode
        
        mode_text = "调试模式" if new_debug_mode else "生产模式"
        logger.info(f"🔄 调试模式已切换为: {mode_text}")
        
        return {
            "success": True,
            "message": f"已切换为{mode_text}",
            "minimax_debug_mode": new_debug_mode,
            "current_mode": mode_text,
            "timestamp": int(time.time()),
        }
    except Exception as e:
        logger.error(f"切换调试模式失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"切换调试模式失败: {str(e)}",
        )


@router.options("/text-to-image")
async def text_to_image_options():
    """处理 text-to-image 的 OPTIONS 预检请求"""
    return {"message": "OK"}


@router.post(
    "/text-to-image",
    response_model=TextToImageResponse,
    responses={
        400: {"model": ErrorResponse, "description": "请求参数错误"},
        500: {"model": ErrorResponse, "description": "服务器内部错误"},
    },
    summary="文生图",
    description="根据文本提示词生成图片（使用 MiniMax）",
)
async def text_to_image(request: TextToImageRequest):
    """
    文生图接口
    
    - **prompt**: 文本提示词（必填，1-1000字符）
    - **aspect_ratio**: 图片宽高比（可选，默认1:1，支持: 1:1, 16:9, 9:16, 4:3, 3:4）
    - **response_format**: 响应格式（可选，默认url，支持: url, base64）
    
    Returns:
        TextToImageResponse: 包含生成的图片URL或base64数据和相关信息
    """
    try:
        debug_mode = settings.MINIMAX_DEBUG_MODE
        mode_text = "调试模式" if debug_mode else "生产模式"
        logger.info(f"收到文生图请求（{mode_text}）: {request.prompt[:50]}... (ratio: {request.aspect_ratio})")

        if debug_mode:
            # 调试模式：返回模拟数据
            import time
            import asyncio
            
            # 模拟生成时间
            await asyncio.sleep(2)
            
            # 模拟图片URLs（使用一些示例图片）
            mock_images = [
                "https://picsum.photos/1024/1024?random=1",
                "https://picsum.photos/1024/1024?random=2",
            ]
            
            # 根据宽高比调整图片尺寸
            if request.aspect_ratio == "16:9":
                mock_images = [
                    "https://picsum.photos/1920/1080?random=1",
                    "https://picsum.photos/1920/1080?random=2",
                ]
            elif request.aspect_ratio == "9:16":
                mock_images = [
                    "https://picsum.photos/1080/1920?random=1",
                    "https://picsum.photos/1080/1920?random=2",
                ]
            elif request.aspect_ratio == "4:3":
                mock_images = [
                    "https://picsum.photos/1024/768?random=1",
                    "https://picsum.photos/1024/768?random=2",
                ]
            elif request.aspect_ratio == "3:4":
                mock_images = [
                    "https://picsum.photos/768/1024?random=1",
                    "https://picsum.photos/768/1024?random=2",
                ]
            
            # 只返回一张图片
            selected_image = mock_images[0]
            
            # 构建响应
            images = [
                ImageInfo(url=selected_image, index=0)
            ]

            return TextToImageResponse(
                success=True,
                message="图片生成成功（调试模式）",
                provider="minimax",
                model="image-01",
                images=images,
                revised_prompt=f"优化后的提示词: {request.prompt}",
                usage={
                    "images_generated": 1,
                    "prompt_length": len(request.prompt),
                },
                cost=0.05,
                metadata={
                    "aspect_ratio": request.aspect_ratio,
                    "response_format": request.response_format,
                    "debug_mode": True,
                    "timestamp": int(time.time()),
                },
            )
        else:
            # 生产模式：使用真实的 MiniMax API
            # 创建服务实例
            service = AIServiceFactory.create_text_to_image_service(provider="minimax")

            # 执行生成
            result = await service.generate_image(
                prompt=request.prompt,
                aspect_ratio=request.aspect_ratio,
                response_format=request.response_format,
            )

            # 构建响应
            images = [
                ImageInfo(url=url, index=idx) for idx, url in enumerate(result.images)
            ]

            return TextToImageResponse(
                success=True,
                message="图片生成成功",
                provider=result.provider,
                model=result.model,
                images=images,
                revised_prompt=result.revised_prompt,
                usage=result.usage or {},
                cost=result.cost,
                metadata=result.metadata,
            )

    except ValueError as e:
        logger.error(f"参数验证错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )
    except Exception as e:
        logger.error(f"文生图失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"图片生成失败: {str(e)}",
        )


@router.get(
    "/providers",
    summary="获取可用提供商",
    description="获取支持文生图功能的 AI 提供商列表",
)
async def get_providers():
    """获取可用的 AI 提供商"""
    providers = AIServiceFactory.get_available_providers("text-to-image")
    return {
        "feature": "text-to-image",
        "providers": providers,
        "default": "minimax",
    }


@router.get(
    "/models",
    summary="获取可用模型",
    description="获取 MiniMax 支持的文生图模型列表",
)
async def get_models():
    """获取可用的模型"""
    return {
        "provider": "minimax",
        "models": [
            {
                "id": "image-01",
                "name": "MiniMax 文生图",
                "feature_type": "text-to-image",
                "supported_aspect_ratios": [
                    {"ratio": "1:1", "description": "正方形 (1024x1024)"},
                    {"ratio": "16:9", "description": "横向宽屏 (1920x1080)"},
                    {"ratio": "9:16", "description": "竖向全屏 (1080x1920)"},
                    {"ratio": "4:3", "description": "传统横向 (1024x768)"},
                    {"ratio": "3:4", "description": "传统竖向 (768x1024)"},
                ],
                "response_formats": ["url", "base64"],
                "max_prompt_length": 1000,
            }
        ],
    }

